<template>
  <el-dialog
    :title="rowSubjectName !== '' ? '修改学科' : '新增学科'"
    :visible="showDialog"
    width="400px"
    @close="closeDialog"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="活动名称" prop="input">
        <el-input v-model="form.input" placeholder="请输入学科名称" />
      </el-form-item>
      <el-form-item label="是否显示">
        <el-switch
          v-model="form.value"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </el-form-item>
      <el-form-item style="text-align: right">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitBtn">确认</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { addSubjectsApi, editSubjectsApi } from '@/api/subjects'

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    rowSubjectName: {
      type: String,
      default: ''
    },
    rowId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      rules: {
        input: [
          { required: true, message: '学科名称不能为空', trigger: 'blur' }
        ]
      },
      subjectData: {
        id: 0,
        isFrontDisplay: undefined,
        subjectName: ''
      },
      form: {
        input: '',
        value: true
      }
    }
  },
  watch: {
    rowSubjectName(newName) {
      this.form.input = newName
    }
  },
  methods: {
    async submitBtn() {
      if (this.rowSubjectName) {
        // 修改学科
        this.subjectData.id = this.rowId
        this.subjectData.isFrontDisplay = +this.form.value
        this.subjectData.subjectName = this.form.input
        await editSubjectsApi(this.subjectData)
        this.$message.success('修改学科成功')
      } else {
        // 添加学科
        await addSubjectsApi(this.form.input, this.form.value)
        this.$message.success('新增学科成功')
      }
      this.closeDialog()
    },
    closeDialog() {
      this.$emit('update:showDialog', false)
      this.$emit('getSubjectsListFn')
      this.form.input = ''
      this.form.value = true
    }
  }
}
</script>

<style scoped>
span {
  display: inline-block;
  font-weight: 700;
  width: 80px;
}
</style>
